package com.gemini.main.nio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

public class DefaultServerSocketHandler implements ServerSocketHandler {

    private int bufferSize = 1024;

    private String localCharset = "UTF-8";

    public DefaultServerSocketHandler(int bufferSize) {
        this(bufferSize, null);
    }

    public DefaultServerSocketHandler(String localCharset) {
        this(-1, localCharset);
    }

    public DefaultServerSocketHandler(int bufferSize, String localCharset) {
        this.bufferSize = bufferSize > 0 ? bufferSize : this.bufferSize;
        this.localCharset = localCharset == null ? this.localCharset : localCharset;
    }


    @Override
    public void handleAccept(SelectionKey selectionKey) throws IOException {
        //获取channel
        SocketChannel socketChannel = ((ServerSocketChannel) selectionKey.channel()).accept();
        //非阻塞
        socketChannel.configureBlocking(false);
        //注册selector
        socketChannel.register(selectionKey.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(bufferSize));

        System.out.println("建立连接请求......");
    }

    @Override
    public String handleRead(SelectionKey selectionKey) throws IOException {
        /*SocketChannel socketChannel = (SocketChannel) selectionKey.channel();

        ByteBuffer buffer = (ByteBuffer) selectionKey.attachment();
        ByteBuffer readBuffer = ByteBuffer.allocate(1024);

        String receivedStr = "";

        if (socketChannel.read(buffer) == -1) {
            //没读到内容关闭
            socketChannel.shutdownOutput();
            socketChannel.shutdownInput();
            socketChannel.close();
            System.out.println("连接断开......");
        } else {
            //将channel改为读取状态
            buffer.flip();
            //按照编码读取数据
            receivedStr = Charset.forName(localCharset).newDecoder().decode(buffer).toString();
            buffer.clear();

            //返回数据给客户端
            buffer = buffer.put(("received string : " + receivedStr).getBytes(localCharset));
            //读取模式
            buffer.flip();
            socketChannel.write(buffer);
            //注册selector 继续读取数据
            socketChannel.register(selectionKey.selector(), SelectionKey.OP_READ, ByteBuffer.allocate(bufferSize));
        }
        return receivedStr;*/

        // 有数据可读
        // 上面一个 if 分支中注册了监听 OP_READ 事件的 SocketChannel
        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
        ByteBuffer readBuffer = ByteBuffer.allocate(1024);
        String receivedStr = "";
        int num = socketChannel.read(readBuffer);
        if (num > 0) {
            // 处理进来的数据...
            //按照编码读取数据
            receivedStr = Charset.forName(localCharset).newDecoder().decode(readBuffer).toString();
            //System.out.println("收到数据：" + new String(readBuffer.array()).trim());
            ByteBuffer buffer = ByteBuffer.wrap(("received string : " + receivedStr).getBytes());
            socketChannel.write(buffer);
        } else if (num == -1) {
            // -1 代表连接已经关闭
            //没读到内容关闭
            socketChannel.shutdownOutput();
            socketChannel.shutdownInput();
            socketChannel.close();
            System.out.println("连接断开......");
        }
        return  receivedStr;
    }
}
